<?php

/**
 * @Author: wuchenge
 * @Date:   2022-04-24 11:38:23
 * @Email: ligui0506@126.com
 * @Descript:
 */
namespace App\Models;

use App\Libraries\Utils;
use DB;
use Exception;

class Article extends Model
{
    protected $table    = 'articles';
    protected $guarded  = ['id', 'created_at', 'updated_at'];
    protected $fillable = ['title', 'content', 'status', 'thumb'];
    protected $hidden   = ['pivot'];

    const STATUS_YES = 1;
    const STATUS_NO  = 2;

    /**
     * 图片
     * @param [type] $value [description]
     */
    public function setThumbAttribute($value)
    {
        if (!empty($value)) {
            $this->attributes['thumb'] = Utils::setImage($value);
        }
    }

    public function getThumbAttribute($value)
    {
        if (!empty($value)) {
            $value = Utils::getImage($value);
        }
        return $value;
    }

    public function labels()
    {
        return $this->belongsToMany(Label::class, 'article_label', 'article_id', 'label_id');
    }

    /**
     * 删除标签
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function del($id): array
    {
        try {

            DB::transaction(function () use ($id) {
                // 删除
                self::where('id', $id)->delete();
                // 删除关联
                ArticleLabel::where('article_id', $id)->delete();
            });

            return ['status' => true];
        } catch (Exception $e) {
            return [
                'status'  => false,
                'message' => $e->getMessage(),
            ];
        }
    }

    /**
     * 添加文章
     * @param array $data [description]
     */
    public static function add(array $data): array
    {
        try {

            DB::transaction(function () use ($data) {
                // 添加文章
                $article = self::create($data);
                // 关联标签
                $article->labels()->attach($data['label_ids']);
            });

            return ['status' => true];
        } catch (Exception $e) {
            return [
                'status'  => false,
                'message' => $e->getMessage(),
            ];
        }
    }

}
